laravel 7 captcha example

Addcaptcha

Sure! Below is an example of how to implement a simple CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) in Laravel 7 using the popular package `greggilbert/recaptcha`.


Step 1: Install the required package
In your Laravel 7 project, open a terminal and run the following command to install the `greggilbert/recaptcha` package:


```bash

composer require greggilbert/recaptcha

```


Step 2: Get the reCAPTCHA API keys
Go to the reCAPTCHA website (https://www.google.com/recaptcha) and sign up or log in to your Google account. After that, register your website to get the site and secret keys required for reCAPTCHA integration.


Step 3: Configuration
Open the `.env` file in your Laravel project and add the following lines:


```dotenv

RECAPTCHA_SITE_KEY=your-recaptcha-site-key

RECAPTCHA_SECRET_KEY=your-recaptcha-secret-key

```


Step 4: Create a form with CAPTCHA

Now, let's create a simple form with a CAPTCHA field. For this example, let's assume we want to protect the login page.


In your view file, e.g., `resources/views/auth/login.blade.php`, add the following code:


```html




Login



Login



@csrf








{!! Recaptcha::render() !!}







```


Step 5: Validate the CAPTCHA

Now, in your `LoginController`, which should be located at `app/Http/Controllers/Auth/LoginController.php`, add the necessary validation for the CAPTCHA.


```php


namespace App\Http\Controllers\Auth;


use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;

use Validator;

use Auth;


class LoginController extends Controller

{

use AuthenticatesUsers;


protected $redirectTo = '/home';


public function __construct()

{

$this->middleware('guest')->except('logout');

}


protected function validator(array $data)

{

return Validator::make($data, [
'email' => ['required', 'string', 'email', 'max:255'],
'password' => ['required', 'string', 'min:8'],

'g-recaptcha-response' => ['required', 'recaptcha'],

]);

}


protected function credentials(Request $request)

{

return array_merge($request->only($this->username(), 'password'), [

'active' => 1, // Add any additional login conditions if required

]);

}

}

```


Step 6: Routes

Ensure that the `web` middleware group is applied to the login routes in `routes/web.php`.


```php

Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');

```


That's it! Now, your Laravel 7 application should have a simple CAPTCHA implemented on the login page. The user will need to solve the CAPTCHA to log in successfully.